import {
  saveJcybApi,
  getJcybPageApi,
  importJcybDataApi,
  deleteJcybjDataApi,
  updateJcybjDataApi,
  saveSubJcybDataApi,
  updateSubJcybDataApi,
  deleteSubJcybDataApi,
  subJcybPageApi,
  mergeSubJcybDataApi,
  exportJcybDataApi,
  getJcybCountApi
} from './api'
import { connectWebSocket } from '@/utils/web-socket'
import { PriorityOptions, resolutionOption } from '@/assets/data/pathInfo'
import { saveAs } from 'file-saver'


export default {
  components: {},
  data() {
    return {
      PriorityOptions,
      jxTableLoading: false,
      tableLoading: true,
      formInline: {
        demand: ''
      },
      tableData: [],
      currentPage3: 5,
      dialogVisible: false,
      aggregateVisible: false,
      sampleVisible: false,
      labelPosition: 'right',
      sampleData: {},
      aggregateData: {},
      pageCurrent: 1,
      pageSize: 10,
      total: 0,
      fileList: [],
      jxInputData: [],
      jxTableKey: 0,
      multipleSelection: [],
      ysOptions: [
        {
          value: '是',
          label: '是'
        },
        {
          value: '否',
          label: '否'
        }
      ],
      sfppOptions: [
        {
          value: '是',
          label: '是'
        },
        {
          value: '否',
          label: '否'
        }
      ],
      sfhzOptions: [
        {
          value: '是',
          label: '是'
        },
        {
          value: '否',
          label: '否'
        }
      ],
      yxjOptions: [
        {
          value: '高',
          label: '高'
        },
        {
          value: '低',
          label: '低'
        }
      ],
      missionTypeOption: [
        { label: '搜索', value: '搜索' },
        { label: '识别', value: '识别' }
      ],
      // 目标形态
      targetShapeOption: [
        {
          label: '船',
          value: '船'
        },
        {
          label: '机场',
          value: '机场'
        },
        {
          label: '陆地',
          value: '陆地'
        }
      ],
      // 气象条件
      weatherConditionOption: [
        { label: '晴天', value: '晴天' },
        { label: '多云', value: '多云' },
        { label: '雨天', value: '雨天' }
      ],
      zhlxOptions: [
        { label: '光学', value: '光学' },
        { label: 'SAR', value: 'SAR' },
      ],
      gcmsOptions: [
        { label: '海洋目标搜索', value: '海洋目标搜索' },
        { label: '海洋目标详查', value: '海洋目标详查' },
        { label: '陆地目标普查', value: '陆地目标普查' },
        { label: '陆地目标详查', value: '陆地目标详查' },
      ],
      jcybjImportState: false,
      rules: {
        jcybjID: [
          { required: true, message: '请输入决策样本集编号', trigger: 'blur' }
        ],
        xqcj: [{ required: true, message: '请输入需求场景', trigger: 'blur' }],
        mbssdlqy: [
          { required: true, message: '请输入目标所属地理区域', trigger: 'blur' }
        ]
      },
      subRules: {
        jcybID: [
          { required: true, message: '请输入决策样本ID', trigger: 'blur' }
        ],
        rwlx: [{ required: true, message: '请输入任务类型', trigger: 'blur' }],
        mbxt: [{ required: true, message: '请输入目标形态', trigger: 'blur' }],
        qxtj: [{ required: true, message: '请输入气象条件', trigger: 'blur' }],
        gjys: [{ required: true, message: '选择攻击因素', trigger: 'change' }],
        sfhzmb: [
          { required: true, message: '选择是否合作目标', trigger: 'change' }
        ],
        zhlx: [{ required: true, message: '请输入载荷类型', trigger: 'blur' }],
        gcms: [{ required: true, message: '请输入观测模式', trigger: 'blur' }],
        fbl: [{ required: true, message: '请选择分辨率', trigger: 'change' }],
        yxj: [{ required: true, message: '请输入优先级', trigger: 'change' }]
      },
      mergeJcybState: false,
      // 当前条数
      subCurtent: 1,
      // 请求条数
      subSize: 20,
      subtotal: 0,
      jcybjId: 0,
      rowKeyId: [],
      sampleSetTitle: 0, // 样本集的标题
      smapleTitle: 0, // 样本的标题
      dialogCurtent: 1,
      dialogSize: 100,
      dialogtotal: 0,
      subtableLoading: true,
      resolutionOption,
      samplesTotal: 0,
      fileRef: null
    }
  },
  computed: {},
  created() { },
  mounted() {
    this.getJcybPageData(this.formInline)
    // 监听决策样本导入
    this.wsImportJcybj()
    // 监听决策样本合并
    this.mergeWsJcybj()
    // 获取样本总数
    this.getJcybCount()
  },
  methods: {
    // 获取样本总数
    getJcybCount() {
      getJcybCountApi().then(res => {
        if (res.data.code === 200) {
          this.samplesTotal = res.data.data
        }
      })
    },
    handleImportDecision() {
      this.dialogVisible = true
    },
    /**
     * 导入弹窗分页
     * @param val
     */
    dialogHandleCurrentChange(val) {
      this.dialogCurtent = val
      this.jxExcelFile()
    },
    // 导出决策样本
    async handleExportDecision() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请选择要导出的数据')
      }
      if (this.multipleSelection.length > 1) {
        return this.$message.warning('每次只可以导出一条数据')
      }
      this.$message.warning("正在导出")


      const rowValue = this.multipleSelection[0]

      try {
        const response = await exportJcybDataApi({
          id: rowValue.id
        })

        saveAs(
          response.data,
          `${rowValue.jcybjID}-${rowValue.xqcj}-${rowValue.mbssdlqy}.xlsx`
        )
      } catch (error) {
        this.$message.error('下载Excel失败:', error)
      }
    },
    // 控制每次只能展开一个表格
    handleExpendChange(row) {
      if (!this.rowKeyId[0] || row.id !== this.rowKeyId[0]) {
        this.rowKeyId = []
        this.rowKeyId.push(row.id)
      } else {
        this.rowKeyId = []
      }
      this.jcybjId = row.id
      this.subCurtent = 1
      this.subSize = 100
      this.subJcybPageData()
    },
    subJcybPageData() {
      this.subtableLoading = true
      const data = {
        jcybjId: this.jcybjId,
        pageCurrent: this.subCurtent,
        pageSize: this.subSize
      }
      subJcybPageApi(data).then(res => {
        if (res.data.code === 200) {
          this.tableData.forEach((item, index) => {
            if (item.id === this.jcybjId) {
              this.tableData[index].jcybList = res.data.data.records
              this.subtotal = res.data.data.total
              this.subtableLoading = false
            }
          })
        }
      })
    },
    // 合并决策样本
    mergeJcybj() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择需要合并的样本集!')
        return
      }
      if (this.multipleSelection.length < 2) {
        return this.$message.warning('至少选择两个样本集!')
      }
      let jcybjID = ''
      let flag = false
      this.multipleSelection.forEach(item => {
        jcybjID = jcybjID + item.id + ','
        if (!item.subState || item.subState == '0') {
          flag = true
        }
      })
      if (flag) {
        return this.$message.warning("所选的样本集无下无样本!")
      }
      const data = {
        jcybjID: jcybjID
      }
      mergeSubJcybDataApi(data).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功!')
          this.mergeJcybState = false
          this.tableLoading = true
          this.mergeLxJcybj()
        } else {
          this.$message.error('操作失败!')
        }
      })
    },
    // ws监听决策样本合并是否完成
    mergeWsJcybj() {
      connectWebSocket({
        url: window.ipConfig.wsUrl,
        topic: [
          {
            name: '/topic/merageJcybj',
            callback: res => {
              this.mergeJcybState = true
            }
          }
        ]
      })
    },
    // 轮询决策样本集合并
    mergeLxJcybj() {
      let count = 0
      console.log(this.mergeJcybState, '合并状态')
      const invalid = setInterval(() => {
        if (count > 10 || this.mergeJcybState) {
          this.$message.success('合并完成！')
          this.getJcybPageData(this.formInline)
          clearInterval(invalid)
        } else {
          this.$message.warning('正在合并数据，请稍后！')
        }
        count++
      }, 2500)
    },
    // 提交决策样本集
    submitJcybjData() {
      this.$refs.ybjFrom.validate(valid => {
        if (valid) {
          this.pageCurrent = 1
          if (this.aggregateData.id && this.aggregateData.id !== '') {
            this.updateJcybjData()
          } else {
            this.saveJcybData()
          }
          this.aggregateVisible = false
        }
      })
    },
    // 取消决策样本集
    cancelJcybj() {
      this.aggregateData = {}
      this.aggregateVisible = false
    },
    // 保存决策样本
    saveJcybData() {
      saveJcybApi(this.aggregateData).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功!')
          this.getJcybPageData(this.formInline)
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    // 更新决策样本集
    updateJcybjData() {
      updateJcybjDataApi(this.aggregateData).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功!')
          this.getJcybPageData(this.formInline)
        } else {
          this.$message.error('操作失败!')
        }
      })
    },
    // 获取决策样本分页数据
    getJcybPageData(data) {
      this.tableLoading = true
      const query = {
        ...data,
        pageCurrent: this.pageCurrent,
        pageSize: this.pageSize
      }
      getJcybPageApi(query).then(res => {
        if (res.data.code === 200) {
          const data = res.data
          this.tableData = data.data.records
          this.total = data.data.total
          this.tableLoading = false
        }
      })
      this.getJcybCount()
    },
    //判断子数组中是否有数据，没有就不显示展开按钮
    iconHadler({ row }) {
      if (!row.subState || row.subState !== '1') {
        return 'icon-no'
      }
    },
    // 筛选按钮
    onSubmit() {
      this.pageCurrent = 1
      this.getJcybPageData(this.formInline)
    },
    // 重置按钮
    cleanSubmit() {
      this.pageCurrent = 1
      this.formInline = {}
      this.getJcybPageData(this.formInline)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getJcybPageData(this.formInline)
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.getJcybPageData(this.formInline)
    },
    SubHandleSizeChange(val) {
      this.subSize = val
      this.subJcybPageData()
    },
    SubHandleCurrentChange(val) {
      this.subCurtent = val
      this.subJcybPageData()
    },
    // 编辑样本集
    aggregateEdit(val) {
      this.sampleSetTitle = 1
      this.aggregateVisible = true
      Object.keys(val).forEach(key => {
        this.$set(this.aggregateData, key, val[key])
      })
    },
    // 创建样本集
    createYbjData() {
      this.sampleSetTitle = 0
      this.aggregateData = {}
      this.aggregateVisible = true
    },
    sampleEdit(val) {
      this.smapleTitle = 1
      this.sampleVisible = true
      Object.keys(val).forEach(key => {
        this.$set(this.sampleData, key, val[key])
      })
    },
    uploadFileChange(event) {
      let that = this
      let csMax = 0
      if (csMax === 0) {
        if (event.target.files.length > 0) {
          const file = event.target.files[0]
          that.formInline.demand = file.name
          that.$set(that.formInline, 'demand', file.name)
          csMax = 1
        }
      }

    },
    // 选择需要上传的文件
    selectWjButton() {
      let that = this
      if (that.fileRef) {
        that.fileRef.remove() // 上传完成后，删除这个DOM元素
      }
      // 创建一个input标签
      that.fileRef = document.createElement('input')
      // 设置input标签的属性
      that.fileRef.name = 'file'
      // 设置input标签的样式
      that.fileRef.type = 'file'
      // 设置input标签的属性
      that.fileRef.accept = '.xls,.xlsx'
      // 设置input标签的样式
      that.fileRef.style.display = 'none'
      // 将input标签添加到body中
      that.fileRef.click()
      document.body.appendChild(that.fileRef)
      // 监听用户选择文件后的操作
      that.fileRef.addEventListener('change', that.uploadFileChange, false)

      // const changeFile = document.getElementById('fileUpload')
      // changeFile.removeEventListener('change', callbackFn, false)
      // changeFile.click()
      // // 监听文件选择变化
      // changeFile.addEventListener('change', callbackFn, false)
    },
    // 解析excel文件
    jxExcelFile() {
      this.jxTableLoading = true
      const fileInput = this.fileRef
      if (fileInput.files.length > 0) {
        const file = fileInput.files[0]
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', '1')
        formData.append('pageCurrent', this.dialogCurtent)
        formData.append('pageSize', this.dialogSize)
        importJcybDataApi(formData).then(res => {
          if (res.data.code === 200) {
            const data = res.data
            this.jxInputData[0] = data.data
            this.dialogtotal = data.data.ybsl
            this.jxTableKey = Math.random()
            this.jxTableLoading = false
            // 上传文件有脏数据，提示用户
            if (res.data.data.errResult.errNum > 0) {
              this.showErrorMessages(res.data.data.errResult)
            }
            fileInput.remove() // 上传完成后，删除这个DOM元素
          } else {
            this.jxTableLoading = false
            this.$message.error(res.data.message != null ? res.data.message : '操作失败')
          }
        })
      }
    },
    // 显示上传的错误信息
    showErrorMessages(errorMsgs) {
      const errorMessageList = errorMsgs.errMsg

      errorMessageList.unshift(
        `错误信息`
      )

      errorMessageList.unshift(
        `错误条数：${errorMsgs.errNum} 条`
      )

      errorMessageList.unshift(
        `总条目数：${errorMsgs.total} 条`
      )

      const errorMessageElements = errorMessageList.map((message, index) => (
        `<div>${message}</div>`
      )).join("")

      this.$alert(errorMessageElements, '提示', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      })
    },
    // 提交解析后的数据保存
    jxCommitData() {
      if (this.jxInputData.length === 0) {
        this.$message.warning('请先上传文件并解析')
        return
      }
      // 监听导入的数据进度
      this.wsImportJcybj()
      this.$message.warning("正在导入")
      this.tableLoading = true
      const fileInput = this.fileRef
      if (fileInput.files.length > 0) {
        const file = fileInput.files[0]
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', '2')
        importJcybDataApi(formData).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
            this.jcybjImportState = false
            this.lxJcybjImport()
          } else {
            this.$message.error(res.data.message != null ? res.data.message : '操作失败')
            this.tableLoading = false
          }
        })
        this.jxInputData = []
        this.dialogVisible = false
      }
    },
    // ws监听决策样本导入是否完成
    wsImportJcybj() {
      connectWebSocket({
        url: window.ipConfig.wsUrl,
        topic: [
          {
            name: '/topic/jcybjImport',
            callback: res => {
              this.jcybjImportState = true
            }
          }
        ]
      })
    },
    // 轮询决策样本集导入
    lxJcybjImport() {
      let count = 0
      const invalid = setInterval(() => {
        if (count > 10 || this.jcybjImportState) {
          this.$message.success('导入完成！')
          this.getJcybPageData(this.formInline)
          clearInterval(invalid)
        } else {
          this.$message.warning('正在导入数据，请稍后！')
        }
        count++
      }, 2500)
    },
    jxCancell() {
      document.getElementById('fileForm').reset()
      this.formInline.demand = ''
      this.jxInputData = []
      this.dialogVisible = false
    },
    // 批量删除数据
    deleteAllSelectData(val) {
      const idList = []
      if (val.id) {
        idList[0] = val.id
      } else {
        this.multipleSelection.forEach(item => {
          idList.push(item.id)
        })
      }
      const data = {
        ids: idList
      }

      if (idList.length === 0) {
        this.$message.warning('请选择删除项')
        return false
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        deleteJcybjDataApi(data).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
            this.pageCurrent = 1
            this.getJcybPageData(this.formInline)
          } else {
            this.$message.error('操作失败')
          }
        })
      })
    },
    // 勾选回调方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 添加样本子集按钮
    createSubYbjData(val) {
      this.smapleTitle = 0
      this.sampleData = {}
      this.sampleVisible = true
      this.sampleData.jcybjId = val.id
    },
    // 创建样本
    saveSubJcybData() {
      saveSubJcybDataApi(this.sampleData).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功')
          this.getJcybPageData(this.formInline)
          this.sampleVisible = false
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    // 取消决策样本
    cancelSubJcyb() {
      this.$refs.subYbForm.resetFields()
      this.sampleData = {}
      this.sampleVisible = false
    },
    //保存或更新样本
    saveAndUpdateSubJcybData() {
      this.$refs.subYbForm.validate(valid => {
        if (valid) {
          this.subCurtent = 1
          this.rowKeyId = []
          if (this.sampleData.id && this.sampleData.id !== '') {
            this.updateSubJcybData()
          } else {
            this.saveSubJcybData()
          }
        }
      })
    },
    // 更新样本
    updateSubJcybData() {
      updateSubJcybDataApi(this.sampleData).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功')
          this.getJcybPageData(this.formInline)
          this.sampleVisible = false
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    // 删除样本
    deleteSubJcybData(row) {
      const data = {
        ids: [row.id]
      }

      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        deleteSubJcybDataApi(data).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
            this.subCurtent = 1
            this.subJcybPageData()
            this.rowKeyId = []
            this.getJcybPageData(this.formInline)
          } else {
            this.$message.error('操作失败')
          }
        })
      })
    }
  }
}
